package com.writing.controller;

import com.writing.common.Result;
import com.writing.entity.NovelGenre;
import com.writing.service.NovelGenreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 小说类型Controller
 */
@RestController
@RequestMapping("/genres")
public class NovelGenreController {

    @Autowired
    private NovelGenreService novelGenreService;

    /**
     * 获取用户的小说类型列表
     */
    @GetMapping
    public Result<List<NovelGenre>> getGenres(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            // 确保用户有默认类型
            novelGenreService.initDefaultGenres(userId);

            List<NovelGenre> genres = novelGenreService.getGenresByUserId(userId);
            return Result.success(genres);
        } catch (Exception e) {
            return Result.error("获取类型列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取类型详情
     */
    @GetMapping("/{genreId}")
    public Result<NovelGenre> getGenre(@PathVariable Long genreId,
                                      HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            NovelGenre genre = novelGenreService.getGenreById(genreId, userId);
            if (genre == null) {
                return Result.error("类型不存在");
            }
            return Result.success(genre);
        } catch (Exception e) {
            return Result.error("获取类型详情失败: " + e.getMessage());
        }
    }

    /**
     * 根据代码获取类型
     */
    @GetMapping("/code/{code}")
    public Result<NovelGenre> getGenreByCode(@PathVariable String code,
                                            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            NovelGenre genre = novelGenreService.getGenreByCode(code, userId);
            if (genre == null) {
                return Result.error("类型不存在");
            }
            return Result.success(genre);
        } catch (Exception e) {
            return Result.error("获取类型失败: " + e.getMessage());
        }
    }

    /**
     * 创建类型
     */
    @PostMapping
    public Result<NovelGenre> createGenre(@RequestBody @Valid NovelGenre genre,
                                         HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            genre.setUserId(userId);
            NovelGenre createdGenre = novelGenreService.createGenre(genre);
            return Result.success("创建成功", createdGenre);
        } catch (Exception e) {
            return Result.error("创建类型失败: " + e.getMessage());
        }
    }

    /**
     * 更新类型
     */
    @PutMapping("/{genreId}")
    public Result<NovelGenre> updateGenre(@PathVariable Long genreId,
                                         @RequestBody NovelGenre genre,
                                         HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            genre.setId(genreId);
            genre.setUserId(userId);
            NovelGenre updatedGenre = novelGenreService.updateGenre(genre);
            if (updatedGenre == null) {
                return Result.error("类型不存在或无权限修改");
            }
            return Result.success(updatedGenre);
        } catch (Exception e) {
            return Result.error("更新类型失败: " + e.getMessage());
        }
    }

    /**
     * 删除类型
     */
    @DeleteMapping("/{genreId}")
    public Result<String> deleteGenre(@PathVariable Long genreId,
                                     HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            boolean deleted = novelGenreService.deleteGenre(genreId, userId);
            if (!deleted) {
                return Result.error("类型不存在或无权限删除");
            }
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("删除类型失败: " + e.getMessage());
        }
    }

    /**
     * 初始化默认类型
     */
    @PostMapping("/init-defaults")
    public Result<String> initDefaultGenres(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            novelGenreService.initDefaultGenres(userId);
            return Result.success("默认类型初始化成功");
        } catch (Exception e) {
            return Result.error("初始化默认类型失败: " + e.getMessage());
        }
    }

}
